package com.baidu.sggc.service;

import com.baidu.sggc.entity.UserContext;
import com.baidu.sggc.entity.Vote;
import com.baidu.sggc.mapper.VoteMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.time.LocalDateTime;
import java.util.Objects;
import org.springframework.beans.factory.annotation.Autowired;

public class VoteService {
  @Autowired
  private VoteMapper voteMapper;


  /**
   * 用户点赞 点踩
   * 根据模块ID和模块类型：第一次新增  第二次编辑
   * @param vote 用户点赞实体
   */
  public void updateVote(Vote vote) {
    QueryWrapper<Vote> wrapper = new QueryWrapper<>();
    wrapper.eq("biz_id", vote.getBizId())
            .eq("type", vote.getType());
    Vote voteInfo = voteMapper.selectOne(wrapper);

    vote.setVersion(LocalDateTime.now());
    // 注入用户信息（可选，记录是谁进行了点赞或点踩）
    String userId = UserContext.getUserId();
    if (Objects.isNull(voteInfo)) {
      vote.setCreateTime(LocalDateTime.now());
      // 设置创建人信息
      if (userId != null) {
        vote.setCreateId(userId);
      }
      voteMapper.insert(vote);
    } else {
      vote.setUpdateTime(LocalDateTime.now());
      voteMapper.updateById(vote);
    }
  }


  /**
   * 查询用户点踩点赞
   * @param vote bean
   * @return
   */
  public Vote selectVote(Vote vote) {
    QueryWrapper<Vote> wrapper = new QueryWrapper<>();
    wrapper.eq("biz_id" , vote.getBizId())
        .eq("type" , vote.getType());
    Vote voteInfo = voteMapper.selectOne(wrapper);
    return voteInfo;
  }
}
